#include "ThreadPool.h"
const int THREAD_MAX_THRESHHOLD = 1024;
const int TASK_MAX_THRESHHOLD = INT32_MAX;
ThreadPool::ThreadPool()
    :initThreadSize_(0),
    threadSize_(0),
    taskSize_(0)
     threadSizeThreshHold_(THREAD_MAX_THRESHHOLD),
     taskSizeThreshHold_(TASK_MAX_THRESHHOLD),
     mode_(PoolMode::MODE_FIXED)
{   

}
void ThreadPool::start(size_t initThreadSize){
    initThreadSize_=initThreadSize;
    //创建线程对象
    for(size_t i=0;i<initThreadSize_;i++){
        auto ptr= std::make_unique<Thread>(std::bind(&ThreadPool::threadFunc,this)); 
        threads_.emplace(std::move(ptr));
    }   
    //启动线程
    for(auto begin=threads_.begin();begin!=threads_.end();++begin){
        (*begin)->start();
        threadSize_++;
    }
}
//每个线程启动后都会执行这个函数入口
void ThreadPool::threadFunc(){
    while(true){
        std::unique_lock<std::recursive_mutex> lock(mutex_);
        notEmpty_.wait(lock,[this](){
                       taskSize_>0;
                       });
        std::shared_ptr<Task> task= taskQue_.front();
        taskQue_.pop();
        --taskSize_;
        //释放锁
        lock.unlock();
        //执行任务
        task->run();
    }
}

void ThreadPool::submitTask(std::shared_ptr<Task>& task){
    //获取锁
    std::unique_lock<std::recursive_mutex> lock(mutex_);
    if(!notFull_.wait_for(lock,std::chrono::seconds(1),[this](){
                          return taskSize_<taskSizeThreshHold_;
                          })){
        std::cerr << "task queue is full, submit task fail." << std::endl;
    }
    taskQue_.emplace(task);
    ++taskSize_;
    notEmpty_.notify_all();

}
ThreadPool::Thread::Thread(ThreadFunc && func)
    :func_(std::move(func))
{

}

void ThreadPool::Thread::start(){
    std::thread th(func_);
    th.detach();
}
